<template>
  <div>
    <cube-form :model="model" :schema="schema" @submit="submitHandler" @validate="validateHandler"></cube-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      model: {
        //数据模型
        username: "",
        password: ""
      },
      schema: {
        // 表单结构模型
        fields: [
          {
            type: "input",
            component: "",
            label: "用户名",
            modelKey: "username",
            props: {
              placeholder: "请输入用户名"
            },
            rules: {
              // 校验规则
              required: true,
              min: 5,
              max: 10
            },
            trigger: "blur",
            message: {
              requires: "用户名位必填项",
              min: "最少位5个字符",
              maxm: "最多10个字符"
            }
          },
          {
            type: "input",
            component: "",
            label: "密码",
            modelKey: "password",
            props: {
              placeholder: "请输入密码",
              type: "password",
              eye: { open: false } //密码可见
            },
            rules: {
              // 校验规则
              required: true,
              min: 6
            },
            trigger: "blur",
            message: {
              required: "密码为必填项",
              min: "密码最少输入6位"
            }
          },
          {
            // 登录 按钮
            type: "submit",
            label: "登录"
          }
        ]
      }
    };
  },
  methods: {
    async submitHandler(e) {
      e.preventDefault();
      // 效验成功 ，才会 打印出来
      console.log("登录");
      console.log("eee", e);
      // 异步请求，返回个promise
      // 用 async修饰一下，等待响应结果
      // const res = await this.$http.get("/api/login", {
      //   params: {
      //     username: this.model.username,
      //     password: this.model.password
      //   }
      // });

      // post 请求 参数放到请求体里，没体积 长度上的限制
      //  后台也要相对的修改
      const res = await this.$http.post("/api/login", {
        username: this.model.username,
        password: this.model.password
      });
      // 数据解构
      console.log("res", res);

      const { code, token, message } = res.data;
      if (code === 0) {
        //登录成功，令牌持久化,只要token没过期，就可一直用
        localStorage.setItem("token", token);
        // 存入 state
        this.$store.commit("setToken", token);

        // 回跳
        const redirect = this.$route.query.redirect || "/";
        console.log("redirect", redirect);
        this.$router.push(redirect);
      } else {
        //登录 失败 cube-ui提供的全局api
        const toast = this.$createToast({
          time: 2000,
          txt: message || "登录失败",
          type: "error"
        });

        toast.show();
      }
    },
    validateHandler(ret) {
      console.log("效验", ret);
    }
  }
};
</script>

<style lang="scss" scoped>
</style>